﻿
//文档就绪函数
$(function () {
    //初始化表格
    ShowProcessProcedures();
});

//工序列表展示
function ShowProcessProcedures() {
    layui.use(function () {

        // 点击导出按钮
        document.getElementById('exportBtn').addEventListener('click', function () {
            var checkStatus = table.checkStatus('ProcessProceduresTable');  // 获取当前表格的选中状态
            var selectedData = checkStatus.data;  // 获取选中的数据
            if (selectedData.length === 0) {
                alert('请先选择要导出的数据!');
                return;
            }
            var filteredData = selectedData.map(function (item) {
                // 创建一个新对象，只包含您想要的属性
                return {
                    '工序Id': item.productionProcessesId,
                    '工序名称': item.productionProcessesName,
                    '工序编号': item.productionProcessesNumber,
                    '工序说明': item.specification,
                    '状态': item.status,
                    '备注': item.notes,
                    "工序分类": item.processClassification,
                    '创建时间': item.createdDate,
                };
            });

            // 使用 XLSX 导出选中的数据
            var wb = XLSX.utils.book_new();
            var ws = XLSX.utils.json_to_sheet(filteredData); // 将选中的数据转换为工作表
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

            // 导出为 Excel 文件
            XLSX.writeFile(wb, '工人列表.xlsx');
        });

        var table = layui.table;
        var ProductionProcessesNumber = $("#ProductionProcessesNumber").val();
        var ProductionProcessesName = $("#ProductionProcessesName").val();
        var Status = $("#Status").val();

        //执行渲染
        table.render({
            elem: '#ProcessProceduresTable',
            page: {
                limit: 15, //每页显示的条数
                limits: [15, 20, 25, 30] //每页显示条数的选择项
            },
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'productionProcessesName', title: '工序名称', width: 130 },
                { field: 'productionProcessesNumber', title: '工序编号', width: 130 },
                { field: 'specification', title: '工序说明', width: 130 },
                { field: 'status', title: '状态', width: 130 },
                { field: 'notes', title: '备注', width: 130 },
                { field: 'createdDate', title: '创建时间', width: 160 },
                {
                    field: '', title: '操作', width: 130, templet: function (d) {
                        return '<a class="layui-btn layui-btn-xs" lay-event="edit" onclick="EditProcessProcedure(' + d.productionProcessesId + ')">编辑</a>' +
                            '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" onclick="DeleteProcessProcedure(' + d.productionProcessesId + ')">删除</a>';
                    }
                }
            ]],
            //数据接口
            data: []
        });
        //请求数据
        $.ajax({
            url: '../ProcessProcedures/GetProductionProcessPageList',
            type: "get",
            data: {
                PageIndex: 1,
                PageSize: 15,
                ProductionProcessesName: ProductionProcessesName,
                ProductionProcessesNumber: ProductionProcessesNumber,
                Status: Status
            },
            success: function (data) {
                data = JSON.parse(data);
                console.log(data);
                table.reload('ProcessProceduresTable', {
                    pagge: {
                        limit: 15,
                        limits: [15, 20, 25, 30]
                    },
                    data: data.data.list
                });
            },
            error: function () {
                console.log("请求失败");
            }

        });
    });
}

//删除工序
window.DeleteProcessProcedure = function (id) {
    var token = localStorage.getItem("token");
    var data = JSON.stringify({
        productionProcessesId: id,
        deletedBy: "张三"
    })
    layer.confirm('确定要删除该数据吗？', function(index) {
            $.ajax({
                url: '../ProcessProcedures/DeleteProductionProcess',
                type: "Post",
                data: { data: data, token:token },
                success: function (res) {
                    console.log(res);
                    var res = JSON.parse(res);
                    if (res.code===1) {
                        layer.msg('删除成功', { icon: 1 });
                        ShowProcessProcedures();
                    } else {
                        layer.msg('删除失败', { icon: 2 });
                    }
                },
                error: function () {
                    layer.msg('删除失败,请稍后重试', {
                        time: 2000,
                        icon: 2
                    });
                }
            });
            layer.close(index);
        });
}

//批量删除工序
window.BatchDeleteProcessProcedure = function BatchDeleteProcessProcedure() {
    var checkStatus = layui.table.checkStatus('ProcessProceduresTable');
    var token = localStorage.getItem("token");
    var ids = checkStatus.data.map(function (item) { return item.productionProcessesId; });
    console.log(ids);
    if (ids.length === 0) {
        layer.msg("请至少选择一条要删除的数据", { icon: 2 });
        return;
    }

    var data = JSON.stringify({
        ids: ids,
        //token:token,
        deletedBy: "张三"
    })

    layer.confirm('确定要批量删除选中的 ' + ids.length + ' 条数据吗？', function (index) {
        //向服务端发送删除指令
        $.ajax({
            url: '../ProcessProcedures/BatchDeleteProductionProcess', //请求地址
            type: "Post",
            data: { data: data ,token:token }, //发送数据
            success: function (res) {
                console.log(res);
                var res = JSON.parse(res);
                if (res.code === 1) {
                    layer.msg('批量删除成功', { icon: 1 });
                    ShowProcessProcedures();
                } else {
                    layer.msg('批量删除失败：' + res.message, { icon: 2 });
                }
            },
            error: function () {
                layer.msg('删除失败,请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
}

var obj = {
    ProductionProcessesId: '',
    ProductionProcessesName: '',
    ProductionProcessesNumber: '',
    Status: '',
    Specification: '',
    Notes: '',
    CreatedBy:'',
    CreatedDate:'',
    UpdatedBy: '',
    DeletedBy:'',
    DeletedDate: '',
    IsDeleted: false
};

//全局变量
//反填修改工序信息
layui.use(['table', 'form','layer'], function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    //编辑工序--反填+修改
    window.EditProcessProcedure = function (productionProcessesId) {
        var token = localStorage.getItem("token");
        //先根据id获取数据
        $.ajax({
            type: "Get",
            url: "../ProcessProcedures/ReverseProductionProcess",
            data: { productionProcessesId: productionProcessesId, token: token },
            success: function (res) {
                var data = JSON.parse(res).data; // 确保 res.data 是一个对象
                console.log(data);

                // 直接填充表单和 obj 对象
                $("#ProductionProcessesId").val(data.productionProcessesId);
                $("#ProductionProcessesNameTwo").val(data.productionProcessesName);
                $("#ProductionProcessesNumberTwo").val(data.productionProcessesNumber);
                $("[name='Status'][value='" + data.status + "']").prop('checked', true); // 设置状态
                $("#Specification").val(data.specification);
                $("#Notes").val(data.notes);

                obj = {
                    ProductionProcessesId: data.productionProcessesId,
                    ProductionProcessesName: data.productionProcessesName,
                    ProductionProcessesNumber: data.productionProcessesNumber,
                    Status: data.status,
                    Specification: data.specification,
                    Notes: data.notes,
                    CreatedBy: data.createdBy,
                    CreatedDate: data.createdDate,
                    UpdatedBy: data.updatedBy || '', // 假设可能未提供 updatedBy
                    DeletedBy: data.deletedBy,
                    DeletedDate: data.deletedDate,
                    IsDeleted: data.isDeleted
                };
            }
        });
        layer.open({
            type: 1,//iframe层
            title: '编辑工序信息',
            shadeClose: true,  // 点击遮罩区域，关闭弹层
            shade: 0.8,//遮罩透明度
            area: ['600px', '500px'],//弹层大小
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `<form class="layui-form" action="">

            <div class="layui-form-item">
                <label class="layui-form-label">工序编号</label>
                <div class="layui-input-inline">
                    <input type="text" id="ProductionProcessesNumberTwo" name="ProductionProcessesNumber" required lay-verify="required" placeholder="请输入工序编号" style="width: 300px;" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">工序名称</label>
                <div class="layui-input-block">
                    <input type="text" id="ProductionProcessesNameTwo" name="ProductionProcessesName" required lay-verify="required" placeholder="请输入工序名称" style="width: 300px;" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <input type="radio" name="Status" value="启用" title="启用">
                    <input type="radio" name="Status" value="禁用" title="禁用">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">工序说明</label>
                <div class="layui-input-block">
                    <textarea id="Specification" name="Specification" placeholder="请输入工序说明" style="width: 300px;" class="layui-textarea"></textarea>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea id="Notes" name="Notes" placeholder="请输入备注" class="layui-textarea" style="width: 300px;" ></textarea>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block" style="float:right">
                    <button class="layui-btn" lay-submit lay-filter="demo-login">提交修改</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>`,
            success: function () {
                var objTwo = {
                    ProductionProcessesId: '',
                    ProductionProcessesName: '',
                    ProductionProcessesNumber: '',
                    Status: '',
                    Specification: '',
                    Notes: '',
                    CreatedBy: '',
                    CreatedDate: '',
                    UpdatedBy: '',
                    DeletedBy: '',
                    DeletedDate: '',
                    IsDeleted: false
                };
                //对弹层中的表单进行初始化渲染
                form.render();
                //监听提交
                form.on('submit(demo-login)', function (data) {
                    //console.log(data.field);
                    var field = data.field;
                    console.log(field);
                    //修改数据
                    objTwo.ProductionProcessesId = obj.ProductionProcessesId;
                    objTwo.ProductionProcessesName = field.ProductionProcessesName;
                    objTwo.ProductionProcessesNumber = field.ProductionProcessesNumber;
                    objTwo.Status = field.Status;
                    objTwo.Specification = field.Specification;
                    objTwo.Notes = field.Notes;
                    objTwo.CreatedBy = obj.CreatedBy;
                    objTwo.CreatedDate = obj.CreatedDate;
                    objTwo.UpdatedBy = "张三";
                    objTwo.DeletedBy = obj.DeletedBy;
                    objTwo.DeletedDate = obj.DeletedDate;
                    objTwo.IsDeleted = obj.IsDeleted;
                    console.log(objTwo);
                    //发送请求
                    $.ajax({
                        url: '../ProcessProcedures/UpdateProductionProcess',
                        type: "Post",
                        data: { objTwo, token },
                        success: function (res) {
                            console.log(res);
                            var res = JSON.parse(res);
                            if (res.code === 1) {
                                layer.alert("修改成功");
                                setTimeout(function () {
                                    location.reload();
                                }, 2000);
                            } else {
                                layer.msg('修改失败：' + res.message, { icon: 2 });
                            }
                        },
                        error: function () {
                            layer.msg('修改失败,请稍后重试', {
                                time: 2000,
                                icon: 2
                            });
                        }
                    });
                    //阻止表单跳转
                    return false;
                });
            }
        });
    }
});